#!/bin/bash

kernver=${KERNVER:-$(uname -r)}
nvidia_ver=whatever

LOG="/var/log/nvidia-install.log"

install_module(){
    echo ""
    echo -e '\E[37;44m'"\033[1mBuilding nvidia package for ${kernver} kernel ...\033[0m"
    echo "--------"
    if [ ! -d "/lib/modules/${kernver}/build" ]; then
      echo -e '\E[37;44m'"\033[1mKernel header files are absent: directory /lib/modules/${kernver}/build doesn't exist! Game over\033[0m"
      echo "--------"
      return 1
    fi
    workdir=$(mktemp -du /tmp/nvidia.XXXXXX)
#    set -x
    cp "/usr/share/nvidia/build_mod" "${workdir}" -R
    cd "$workdir"
    sed -i -e "s/_kernver=.*/_kernver=${kernver}/" PKGBUILD
    sed -i -e "s/pkgver=.*/pkgver=${nvidia_ver}/" PKGBUILD
    sed -i -e "s/pkgrel=.*/pkgrel=${kernver/-/_}/" PKGBUILD
    if [ "${LOGNAME}" = "root" ]; then
      if [ "${user}" = "root" ]; then
       /usr/bin/makepkg -f -c --asroot || return 1
     	 else	
    	   chown ${user}:video ${workdir}
    	   chown ${user}:video ${workdir}/* >> /dev/null 2>&1
    	   su - ${user} -c "cd ${workdir} && /usr/bin/makepkg -f -c" || return 1
      fi
      else
	 /usr/bin/makepkg -f -c || return 1
    fi
    echo -e '\E[37;44m'"\033[1mOk. nvidia ${kernver} package built succesfully. Installing ...\033[0m"
    if [ -e /usr/bin/sudo ]; then
        echo -e '\E[37;44m'"\033[1mIf it's asking for password - type YOUR password\033[0m"
        sudo /usr/bin/pacman -Udf ${workdir}/nvidia-${nvidia_ver}-${kernver/-/_}-$(uname -m).pkg.* || return 1
    else
        echo -e '\E[37;44m'"\033[1mIf it's asking for password - type root password\033[0m"
        su - root -c "/usr/bin/pacman -Udf ${workdir}/nvidia-${nvidia_ver}-${kernver/-/_}-$(uname -m).pkg.*" || return 1
    fi
    rm -rf "${workdir}"
#    set +x
    echo -e '\E[37;44m'"\033[1mDone.\033[0m"
}

build_all_modules(){
    if [ "${LOGNAME}" = "root" ]; then
      echo "Please specify your (unprivileged) user name:"
      read user
    fi
    for p in /lib/modules/*; do
     if [ -d $p/build ] && [ -d $p/kernel ]; then
      /usr/bin/nvidia_build_module ${p##*/lib/modules/} ${user}
     fi
    done
}
remove_module(){
    echo "Removing unused nvidia-{kernver} packages ..."
    for p in /lib/modules/*; do
	if [ ! -d $p/kernel ]; then
	    if [ -e $p/video/nvidia.ko ]; then
		  /usr/bin/pacman -Rd nvidia
	    fi
	fi
    done
}
remove_all_modules(){
    for p in /lib/modules/*; do
	if [ -e $p/video/nvidia.ko ]; then
	      /usr/bin/pacman -Rd --noconfirm nvidia
	fi
    done
}

auto_recompile(){
    # add hook nvidia to mkiniticpio
    hooks=$(grep ^HOOKS /etc/mkinitcpio.conf | grep nvidia)
    if [ "$hooks" = "" ]; then
        # add hook nvidia
        sed 's/^HOOKS="\([^"]*\)"/HOOKS="\1 nvidia"/' -i /etc/mkinitcpio.conf
    fi
    #add kernel26-headers to SyncFirst array of pacman.conf
    heads=$(grep ^SyncFirst /etc/pacman.conf | grep kernel26-headers)
    if [ "$heads" = "" ]; then
        # add heads
	sed '/^SyncFirst/s|$| kernel26-headers|' -i /etc/pacman.conf
    fi
    echo "----------------------------------------------------------------"
    echo "Answer 'Yes' whenever pacman ask you about updating"
    echo "'kernel26-headers' in first place"
    echo "----------------------------------------------------------------"
}

auto_recompile_off(){
    # remove hook nvidia
    sed '/^HOOKS/s/ *nvidia//' -i /etc/mkinitcpio.conf
    # remove heads
    sed '/^SyncFirst/s/ *kernel26-headers//' -i /etc/pacman.conf
    echo "Auto re-compilation is Disabled."
}

case "$1" in
    help|--help)
        echo "usage: $0 {version|all|remove|remove_all|auto|autooff}"
        echo "- with no specified kernel version it will use the current kernel version to build module"
	echo "- all will try to build nvidia modules for all working system's kernels"
        echo "- remove is removing unused nvidia-{kernver} packages"
        echo "- remove_all is removing all nvidia-{kernver} packages"
        echo "- auto will turn ON 'auto re-compilation of nvidia module with every kernel update'"
        echo "- autooff will turn off auto re-compilation of nvidia module"
        ;;
    remove)
        remove_module
        ;;
    remove_all)
        remove_all_modules
        ;;
    auto)
	auto_recompile
	;;
    autooff)
	auto_recompile_off
	;;
    all)
	build_all_modules
	;;
    *)
        test "$1" != "" && kernver="$1"
	if [ "$2" != "" ]; then user="$2"
          elif [ "${LOGNAME}" = "root" ]; then
	      echo "Please specify your (unprivileged) user name:"
	      read user
	fi
        install_module
        ;;
esac

